package async.callback;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Console;

/**
 * @author jiangwz
 * @create 2020/10/15.
 */
public class TestCallback {


    public static void main(String[] args) throws ExecutionException, InterruptedException {

        String receiveMsg = "你好";
        Console.log("time:{}, client2server->{}", DateUtil.now(), receiveMsg);

        /**
         * 无返回值时用 runAsync
         */
        CompletableFuture<Void> async = CompletableFuture.runAsync(() -> decodeMsg(receiveMsg, new CallBack<String>() {
            @Override
            public void onSuccess(String msg) {
                sendTo(msg);
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }
        }));


        Console.log("end");

        async.get();
    }

    public static void sendTo(String msg) {
        Console.log("time:{}, server2client->{}", DateUtil.now(), msg);
    }

    private static void decodeMsg(String receiveMsg, CallBack<String> callBack) {
        try {
            TimeUnit.SECONDS.sleep(3);
//            System.out.println(3/0);
            callBack.onSuccess("you too buddy !!!");
        } catch (Exception e) {
            callBack.onError(e);
        }
    }
}
